package api

import (
	"context"
	"log/slog"

	"github.com/gin-gonic/gin"

	"torler.com/qingyue/apps/backend/config"
	"torler.com/qingyue/apps/backend/internal/transport/http/handler"
	"torler.com/qingyue/pkg/logger"
	"torler.com/qingyue/pkg/runtime"
)

type ApiManager struct {
	config     *config.HTTPConfig
	engine     *gin.Engine
	server     *runtime.HttpServer
	log        *slog.Logger
	handlerMgr *handler.HandlerManager
}

func NewApiManager(config *config.HTTPConfig, handlerMgr *handler.HandlerManager) *ApiManager {
	return &ApiManager{
		config:     config,
		engine:     gin.Default(),
		log:        logger.Default(),
		handlerMgr: handlerMgr,
	}

}

// Init 初始化处理器管理器
func (m *ApiManager) Init() error {
	host := m.config.Host
	port := m.config.Port
	m.server = runtime.NewHttpServer(m.engine, host, port, m.log)
	// 在这里可以注册路由和中间件
	m.initMiddleware()
	m.initRoutes()

	return nil
}

// 获取 HttpServer
func (m *ApiManager) GetServer() *runtime.HttpServer {
	return m.server
}

func (m *ApiManager) Start() error {

	return m.server.Start(context.Background())
}
